-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
43 lines (35 loc) · 1.26 KB
/
Solution.java
File metadata and controls
43 lines (35 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.Scanner;
public class CoinChange {
// Function to find the minimum number of coins
public static void findMinCoins(int[] coins, int amount) {
int count = 0;
System.out.print("Coins used: ");
for (int coin : coins) {
while (amount >= coin) {
amount -= coin;
System.out.print(coin + " ");
count++;
}
}
if (amount > 0) {
System.out.println("\nCannot make the exact amount with the given denominations.");
} else {
System.out.println("\nMinimum number of coins needed: " + count);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the number of coin denominations
System.out.print("Enter the number of coin denominations: ");
int n = scanner.nextInt();
int[] coins = new int[n];
System.out.println("Enter the coin denominations in descending order: ");
for (int i = 0; i < n; i++) {
coins[i] = scanner.nextInt();
}
// Input the amount
System.out.print("Enter the amount: ");
int amount = scanner.nextInt();
findMinCoins(coins, amount);
}
}